<template>
  <view>
    <view class="navbar-cnm">
      <view class='nav-left'>
        <uni-icons type="arrow-left" size="30" color="#303133"
          @click="redirectToMemorialHall(meMemorialId)"></uni-icons>
      </view>
      <view class='nav-center'>
        <uv-row class="inp-search">
          <uv-col>
            {{aiTitle.him}}
          </uv-col>
        </uv-row>
      </view>
      <view class='nav-right'>
        <view class="times ml-normal">
          <text class="count">
            剩余{{userInfo.aiTrialNum}}数
          </text>
          <uv-icon name="integral-fill" color="#0cb26a" size="28"></uv-icon>
        </view>
        <view class="ml-normal" @click="isShowMenu = true">
          <uv-icon name="setting-fill" color="#313133" size="28"></uv-icon>
        </view>
        <view class="menu" v-if="isShowMenu" @click="isShowMenu = false">
          <div class="show-box">
            <!-- <view class="item" @click="">
              <uv-icon class='icon' name="file-text" color="#FFF" size="20"></uv-icon>
              聊天记录
            </view> -->
            <view class="item" @click="redirectToAiLogin(meMemorialId, aiTitle.me, aiTitle.him)">
              <uv-icon class='icon' name="edit-pen" color="#FFF" size="20"></uv-icon>
              修改称谓
            </view>
            <view class="item" @click="navigateToRecharge()">
              <uv-icon class='icon' name="red-packet" color="#FFF" size="20"></uv-icon>
              充值缅怀币
            </view>
          </div>
        </view>
      </view>
    </view>

    <view class="ai-dialogue">
      <view class="box-1" id="list-box">
        <!-- <view class="tips size_12 pt-normal" v-if="!aiTitle.talkList.length">
          <uv-text align='center' @tap="getHistoryMsg" type="primary" :customStyle="{height:'auto'}"
            text="点击加载历史数据"></uv-text>
        </view> -->
        <view class="talk-list">
          <view v-for="(item,index) in (aiTitle.talkList || []).filter(o=>newTime - Number(o.id) < aiExp)" :key="index"
            :id="`msg-${item.id}`">
            <view class="item flex_col" :class=" item.type == 1 ? 'push':'pull' ">
              <!-- <image :src="item.pic" mode="aspectFill" class="pic"></image> -->
              <uv-avatar :customStyle="{background:'#fff', padding:'2px'}" :src="item.pic"></uv-avatar>
              <view class="content">{{item.content}}</view>
            </view>
          </view>
        </view>
      </view>
      <view class="box-2">
        <view class="flex_col">
          <view class="flex_grow">
            <input type="text" class="content" v-model="content" placeholder="请输入聊天内容" placeholder-style="color:#DDD;"
              :cursor-spacing="6">
          </view>
          <button :class="['send', {'disabled':sendFlag}]" @tap="send" :disabled="sendFlag">发送</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
  import {
    nextTick,
    onMounted,
    ref,
  } from "vue";
  import {
    redirectToMemorialHall,
    redirectToAiLogin,
    navigateToRecharge
  } from "@/assets/scripts/navigate.js";
  import {
    getItem,
    setItem,
    aiExp,
    aiTitleDemo
  } from "@/assets/scripts/aiStorage.js"
  import {
    memorialHallApi,
  } from "@/assets/api/other/memorialHall.js"
  import {
    sendApi,
    getSystem,
  } from "@/assets/api/other/aiDialogue.js"
  import {
    getInfo2Api,
  } from "@/assets/api/other/recommend.js"
  import {
    useRoute
  } from 'vue-router';

  const isShowMenu = ref(false)
  const meMemorialId = ref('')
  const content = ref('')
  const userInfo = ref({})
  const dataSource = ref([])
  const aiTitle = ref(aiTitleDemo)
  const sendFlag = ref(false)
  const newTime = ref(0)

  const storage_init = () => {
    const route = useRoute()
    if (route.query.meMemorialId && route.query.meMemorialId !== 'undefined') {
      meMemorialId.value = route.query.meMemorialId
    }
    newTime.value = new Date().getTime()
    aiTitle.value = getItem(meMemorialId.value)
    nextTick(() => {
      uni.pageScrollTo({
        scrollTop: 999999, // -30 为多显示出大半个消息的高度，示意上面还有信息。
        duration: 300
      });
    })
  }

  // 发送信息
  const send = async () => {
    if (sendFlag.value) {
      return
    }
    if (!content.value) {
      uni.showToast({
        title: '请输入有效的内容',
        icon: 'none'
      })
      return;
    }
    const contentValue = content.value
    content.value = ''
    sendFlag.value = true
    aiTitle.value.talkList.push({
      id: new Date().getTime(),
      content: contentValue,
      pic: userInfo.value.avatar,
      type: 1
    })
    setItem(aiTitle.value)
    nextTick(() => {
      uni.pageScrollTo({
        scrollTop: 999999, // -30 为多显示出大半个消息的高度，示意上面还有信息。
        duration: 300
      });
    })
    try {
      const system = getSystem(dataSource.value.relation, aiTitle.value.me, aiTitle.value.him)
      const res = await sendApi(contentValue, system, meMemorialId.value)
      if (res.code === 200) {
        aiTitle.value.talkList.push({
          id: new Date().getTime(),
          content: res.data,
          pic: dataSource.value.mmImg1,
          type: 2
        })
        setItem(aiTitle.value)
        nextTick(() => {
          uni.pageScrollTo({
            scrollTop: 999999, // -30 为多显示出大半个消息的高度，示意上面还有信息。
            duration: 300
          });
        })
      } else errToast(res);
    } catch (e) {
      //TODO handle the exception
      errToast(e)
    } finally {
      await userInfo_init()
      sendFlag.value = false
    }
  }

  const errToast = (res) => {
    uni.showToast({
      title: res?.msg || '进程报错',
      icon: 'error'
    })
  }

  const memorialHall_data_init = async () => {
    const res = await memorialHallApi(meMemorialId.value)
    if (res.code === 200) {
      dataSource.value = res.data
    }
  }

  const userInfo_init = async () => {
    const user = uni.getStorageSync('user')
    const res = await getInfo2Api(user.userId)
    if (res.code === 200) {
      userInfo.value = res.user
      uni.setStorageSync('user', res.user)
    }
  }

  onMounted(async () => {
    storage_init() // 存储初始化
    await userInfo_init() // 用户信息初始化
    await memorialHall_data_init() // 馆数据初始化
  })
</script>

<style lang="scss" scoped>
  .navbar-cnm {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    display: flex;
    align-items: center;
    height: 44px;
    padding: 0 15px;
    justify-content: space-between;
    z-index: 100;
    background-color: rgba(255, 255, 255);

    .nav-left {}

    .nav-right {
      display: flex;
      align-items: center;

      .times {
        display: flex;
        align-items: center;
        color: #f3a73f;

        .count {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }

    .nav-center {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
      width: max-content;
      height: max-content;
    }

    .menu {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 20;

      &::after {
        content: "";
        display: block;
        position: absolute;
        top: 44px;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: rgba(0, 0, 0, .4);
      }

      .show-box {
        position: absolute;
        top: 44px;
        background-color: #0cb26a;
        border-radius: 8px;
        padding: 8px;
        right: 15px;
        width: max-content;
        display: flex;
        flex-direction: column;
        z-index: 100;
        color: #fff;

        .item {
          margin: 4px;
          display: flex;

          .icon {
            margin-right: 4px;
          }
        }
      }
    }
  }

  page {
    background-color: #f3f3f3;
    font-size: 28rpx;
    box-sizing: border-box;
    color: #333;
    letter-spacing: 0;
    word-wrap: break-word;
  }

  /* 设置常用元素尺寸规则 */
  view,
  textarea,
  input,
  label,
  form,
  button,
  image {
    box-sizing: border-box;
  }

  /* 按钮样式处理 */
  button {
    font-size: 28rpx;
  }

  /* 取消按钮默认的边框线效果 */
  button:after {
    border: none;
  }

  /* 设置图片默认样式，取消默认尺寸 */
  image {
    display: block;
    height: auto;
    width: auto;
  }

  /* 输入框默认字体大小 */
  textarea,
  input {
    font-size: 28rpx;
  }

  ;

  .ai-dialogue {
    overflow: hidden;
    /* 根元素样式 设置页面背景、字体大小、字体颜色，字符间距、长单词换行 */

    /* 列式弹性盒子 */
    .flex_col {
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: flex-start;
      align-items: center;
      align-content: center;
    }

    /* 行式弹性盒子 */
    .flex_row {
      display: flex;
      flex-direction: column;
      flex-wrap: nowrap;
      justify-content: flex-start;
      align-items: flex-start;
      align-content: flex-start;
    }

    /* 弹性盒子弹性容器 */
    .flex_col .flex_grow {
      width: 0;
      flex-grow: 1;
    }

    .flex_row .flex_grow {
      flex-grow: 1;
    }

    /* 弹性盒子允许换行 */
    .flex_col.flex_wrap {
      flex-wrap: wrap;
    }

    /* 弹性盒子居中对齐 */
    .flex_col.flex_center,
    .flex_row.flex_center {
      justify-content: center;
    }

    /* 列式弹性盒子两端对齐 */
    .flex_col.flex_space {
      justify-content: space-between;
    }

    /* 弹性盒子快速分栏 ,这里非常郁闷 uniapp 居然不支持 * 选择器 */
    .flex_col.flex_col_2>view {
      width: 50%;
    }

    .flex_col.flex_col_3>view {
      width: 33.33333%;
    }

    .flex_col.flex_col_4>view {
      width: 25%;
    }

    .flex_col.flex_col_5>view {
      width: 20%;
    }

    .flex_col.flex_col_6>view {
      width: 16.66666%;
    }

    /* 字体颜色 */
    .color_333 {
      color: #333;
    }

    .color_666 {
      color: #666;
    }

    .color_999 {
      color: #999;
    }

    .color_ccc {
      color: #ccc;
    }

    .color_fff {
      color: #fff;
    }

    .color_6dc {
      color: #6dca6d;
    }

    .color_d51 {
      color: #d51917;
    }

    .color_09f {
      color: #0099ff;
    }

    /* 背景色*/
    .bg_fff {
      background-color: #ffffff;
    }

    /* 字体大小 */
    .size_10 {
      font-size: 20rpx;
    }

    .size_12 {
      font-size: 24rpx;
    }

    .size_14 {
      font-size: 28rpx;
    }

    .size_16 {
      font-size: 32rpx;
    }

    .size_18 {
      font-size: 36rpx;
    }

    .size_20 {
      font-size: 40rpx;
    }

    /* 字体加粗 */
    .font_b {
      font-weight: bold;
    }

    /* 对齐方式 */
    .align_c {
      text-align: center;
    }

    .align_l {
      text-align: left;
    }

    .align_r {
      text-align: right;
    }

    /* 遮罩 */
    .shade {
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      background-color: rgba(0, 0, 0, 0.8);
      z-index: 100;
    }

    /* 弹窗 */
    .shade_box {
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      margin: auto;
      z-index: 101;
      min-width: 200rpx;
      min-height: 200rpx;
    }

    /* 加载数据提示 */
    .tips {
      height: 72rpx;
      line-height: 72rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      text-align: center;
      box-sizing: content-box;
    }

    .box-1 {
      width: 100%;
      height: auto;
      padding-bottom: 100rpx;
      padding-top: 40px;
      box-sizing: content-box;

      /* 兼容iPhoneX */
      margin-bottom: 0;
      margin-bottom: constant(safe-area-inset-bottom);
      margin-bottom: env(safe-area-inset-bottom);
    }

    .box-2 {
      position: fixed;
      left: 0;
      width: 100%;
      bottom: 0;
      height: auto;
      z-index: 2;
      border-top: #e5e5e5 solid 1px;
      box-sizing: content-box;
      background-color: #F3F3F3;

      /* 兼容iPhoneX */
      padding-bottom: 0;
      padding-bottom: constant(safe-area-inset-bottom);
      padding-bottom: env(safe-area-inset-bottom);

      >view {
        padding: 0 20rpx;
        height: 100rpx;
      }

      .content {
        background-color: #fff;
        height: 64rpx;
        padding: 0 20rpx;
        border-radius: 32rpx;
        font-size: 28rpx;
      }

      .send {
        background-color: #42b983;
        color: #fff;
        height: 64rpx;
        margin-left: 20rpx;
        border-radius: 32rpx;
        padding: 0;
        width: 120rpx;
        line-height: 62rpx;

        &:active,
        &.disabled {
          opacity: .75;
        }

      }
    }

    .talk-list {
      padding-bottom: 20rpx;

      /* 消息项，基础类 */
      .item {
        padding: 20rpx 20rpx 0 20rpx;
        align-items: flex-start;
        align-content: flex-start;
        color: #333;

        .pic {
          width: 92rpx;
          height: 92rpx;
          border-radius: 50%;
          border: #fff solid 1px;
        }

        .content {
          padding: 20rpx;
          border-radius: 4px;
          max-width: 500rpx;
          word-break: break-all;
          line-height: 52rpx;
          position: relative;
        }

        /* 收到的消息 */
        &.pull {
          .content {
            margin-left: 32rpx;
            background-color: #fff;

            &::after {
              content: '';
              display: block;
              width: 0;
              height: 0;
              border-top: 16rpx solid transparent;
              border-bottom: 16rpx solid transparent;
              border-right: 20rpx solid #fff;
              position: absolute;
              top: 30rpx;
              left: -18rpx;
            }
          }
        }

        /* 发出的消息 */
        &.push {
          /* 主轴为水平方向，起点在右端。使不修改DOM结构，也能改变元素排列顺序 */
          flex-direction: row-reverse;

          .content {
            margin-right: 32rpx;
            background-color: #a0e959;

            &::after {
              content: '';
              display: block;
              width: 0;
              height: 0;
              border-top: 16rpx solid transparent;
              border-bottom: 16rpx solid transparent;
              border-left: 20rpx solid #a0e959;
              position: absolute;
              top: 30rpx;
              right: -18rpx;
            }
          }
        }
      }
    }
  }
</style>